import axios from 'axios';
import { message } from 'antd';
import { getStorage, removeStorage } from '../utils/storage';
import router from '../router/index';
import useStore from '../zustandStore';
const reSetUserInfo = useStore.getState()?.resetUserInfo;
const axiosInstance = axios.create({
  baseURL: '/apis',
  timeout: 1000,
});
axiosInstance.interceptors.request.use(config => {
  const token = getStorage('token') || '';
  if (token) {
    config.headers.Authorization = `Bearer ${JSON.parse(token)}`;
  }
  return config;
});

axiosInstance.interceptors.response.use(
  res => {
    return res.data;
  },
  err => {
    if (err.response) {
      console.log(err.response);
      const { data } = err.response;
      if (err.response.status === 500) return message.error('网络错误！！');
      if (err.response.status === 401) {
        removeStorage('token');
        reSetUserInfo();
        // window.location.href = '/login';
        //在ts文件中，可以使用这种方式进行跳转 createBrowserRouter
        message.error('用户信息过期，请重新登录！');
        router.navigate('/login');
        return;
      }
      typeof data.message === 'string'
        ? message.error(data.message)
        : message.error(data.message[0]);
    } else if (err.request) {
      // 请求已经发出去，但是没有收到响应
      console.log(err.request);
      message.error('请求超时，请刷新重试');
    } else {
      return Promise.reject(err);
    }
  },
);

export default axiosInstance;
